home *** CD-ROM | disk | FTP | other *** search
- Path: sm-igw1.geoplex.com!usenet
- From: "Jay B. Perry" <jay@geoplex.com>
- Newsgroups: comp.lang.c++
- Subject: const member functions
- Date: Fri, 05 Apr 1996 12:56:06 -0800
- Organization: AT & T
- Message-ID: <316588E6.7D61@geoplex.com>
- NNTP-Posting-Host: 204.160.245.22
- Mime-Version: 1.0
- Content-Type: multipart/mixed; boundary="------------52476AAA66EB"
- X-Mailer: Mozilla 2.0 (Win95; I)
- CC: jay@geoplex.com
-
- This is a multi-part message in MIME format.
-
- --------------52476AAA66EB
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
-
- The attached code doesn't compile, complaining about the non-const
- object's attempt to use a non-const private method (even though a
- const public method with the same name is available).
-
- After leafing through a couple of references I have on C++, I have
- come to the conclusion that the attached C++ code should be
- compilable.
-
- Could someone explain to me why this code doesn't work? I have
- tried compiling it using VC++4.1, SunSoft CC SC3.0.1, g++ 2.7.x
- (I am not sure what the current version is, but I know that the
- most current version was used).
-
- My theory is that it is bagging it because it can't differentiate
- between the int& and the int. But, I also had hoped that in the
- context of the call, it should be able to realize that it doesn't
- have access to the private method, so let's see if there is a public
- method that can be used.
-
- As far as options, I just attempted to produce an executable:
-
- g++ -o file file.cc (using g++ as an example)
-
- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- Jay B. Perry, AT&T | jay@geoplex.com
- 2929 Campus Drive - Suite 350 | V: (415) 577-7747
- San Mateo, CA 94403 | F: (415) 577-7711
-
- --------------52476AAA66EB
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- Content-Disposition: inline; filename="bug.cpp"
-
- //
- // Code starts here
- //
- #include <stdlib.h>
- #include <iostream.h>
-
- class X
- {
- public: // Public methods
- X( ) : _value( 0 ) { }
- X( int value ) : _value( value ) { }
-
- // Public accessor, should be available to all
- // X objects.
- int value( ) const { return _value; }
-
- private: // Private methods
- // Private accessor, should only be available to
- // non-const X objects
- int& value( ) { return _value; }
-
- private: // Private data members
- int _value;
- };
-
- main( )
- {
- X t1( 1 );
- const X t2( 2 );
-
- // The following line results in an error for several
- // compilers, all complaining about an attempt to use
- // the private X::value method!
- cout << t1.value() << endl;
-
- // This line
- cout << t2.value() << endl;
- }
-
- --------------52476AAA66EB--
-
-